package org.tnaggs.project.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.tnaggs.project.model.Team;

public class TeamRepository implements GenericRepository<Team> {
	
	
	private JdbcTemplate template;
	
	public TeamRepository(JdbcTemplate template) {
		this.setTemplate(template);
	}

	public JdbcTemplate getTemplate() {
		return template;
	}

	public void setTemplate(JdbcTemplate template) {
		this.template = template;
	}

	@Override
	public Team findByID(int id) {
		return (Team)template.queryForObject("select * from Team where Team_ID = " + id, new TeamRowMapper());
	}
	
	@Override
	public List<Team> findAll() {
		return (List<Team>)template.query("select * from Team", new TeamRowMapper());
	}
	
	public List<Team> findAllByLeague(long leagueID) {
		return (List<Team>)template.query("select * from Team where League = " + leagueID, new TeamRowMapper());
	}
	
	class TeamRowMapper implements RowMapper<Team> {

		@Override
		public Team mapRow(ResultSet rs, int arg1) throws SQLException {
		
				Team results = new Team();
				results.setLeagueID(rs.getInt("League"));
				results.setTeamID(rs.getInt("Team_ID"));
				results.setContactID(rs.getInt("Coach"));
				results.setName(rs.getString("Name"));
				return results;
		}
	}


	@Override
	public boolean insert(Team newVal) {
		int numResults = template.update("insert into Team (`League`, `Coach`, `Name`) values(" 
	      + newVal.getLeagueID() + "," + newVal.getContactID() + ",'" 
	      + newVal.getName() + "')");
		return numResults == 1;
	}

	@Override
	public boolean delete(int id) {
		int numResults =  template.update("delete from Team where Team_ID = " + id);
		return numResults == 1;
	}

	@Override
	public boolean purge() {
      int numResults = template.queryForInt("select count(*) from Team;");
      int delResults = template.update("delete from Team;");
      return numResults == delResults;
	}

	public Team findByName(String teamName) {
		return (Team)template.queryForObject("select * from Team where name = '" + teamName + "'", new TeamRowMapper());
	}
}
